package com.geping.etl.config.job;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;


/***
 *  调度器配置
 * @author liang.xu
 * @date 2023.7.25
 */
@Component
@Slf4j
public class JobScheduler implements SchedulingConfigurer {


    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        //注册job
        initJobBatch(scheduledTaskRegistrar);
    }


    /**
     * 注册job
     *
     * @param scheduledTaskRegistrar
     */
    private void initJobBatch(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        List<JobTask> jobTasks = JobTaskRegister.getJobTasks();
        if (CollectionUtils.isEmpty(jobTasks)) {
            log.info("无任务注册");
            return;
        }
        for (JobTask jobTask : jobTasks) {
            if (Objects.isNull(jobTask.getTask()) || StringUtils.isBlank(jobTask.getExpression())) {
                log.info("定时任务:{}未注册",jobTask.getClass().getSimpleName());
                continue;
            }
            scheduledTaskRegistrar.addTriggerTask(jobTask.getTask(), triggerContext -> {
                CronTrigger cronTrigger = new CronTrigger(jobTask.getExpression());
                Date nextExecDate = cronTrigger.nextExecutionTime(triggerContext);
                return nextExecDate;
            });
            log.info("定时任务:{}已注册",jobTask.getClass().getSimpleName());
        }
    }
}